import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_app/utils/path_provider_utils.dart';
import 'package:flutter_app/utils/widget_to_image_util.dart';
import 'package:flutter_app/widget/image_watermark.dart';

/**
 * @Description: 把组件 变成 图片的工具类
 * @Author: 下雨了
 * @CreateDate: 2022-08-03 14:46
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-08-03 14:46
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
//
// dependencies:
//   widget_to_image: ^2.0.0
//
class WidgetToImageUtils {
  //私有构造函数
  WidgetToImageUtils._internal();

  //保存单例
  static final WidgetToImageUtils _toImageUtils =
      WidgetToImageUtils._internal();

  //工厂构造函数
  factory WidgetToImageUtils() => _toImageUtils;

  // 通过key 把组件变成 Uint8List
  Future<Uint8List> repaintBoundaryToImage(String address,
    GlobalKey key, {
    double pixelRatio = 1.0,
  }) async {
    Widget widget = ImageWatermark(key: key, address: address);

    ByteData byteData = await WidgetToImage.repaintBoundaryToImage(key, pixelRatio: pixelRatio);

    Uint8List uint8list = byteData.buffer.asUint8List();

    return uint8list;
  }

  // 组件变成 Uint8List  File
  Future<File> widgetToImage(
    String address, {
    String? time,
    String? name,
    Alignment alignment = Alignment.center,
    Size size = const Size(double.maxFinite, double.maxFinite),
    double devicePixelRatio = 1.0,
    double pixelRatio = 1.0,
  }) async {
    // 组件
    Widget widget = ImageWatermark(time: time, name: name, address: address);

    ByteData byteData = await WidgetToImage.widgetToImage(widget,
        alignment: alignment,
        size: size,
        devicePixelRatio: devicePixelRatio,
        pixelRatio: pixelRatio);

    Uint8List uint8list = byteData.buffer.asUint8List();
    String path = await PathProviderUtils().getTempDir() + Platform.pathSeparator + "watermark.png";
    File file = File(path);
    file.writeAsBytesSync(uint8list);
    return file;
  }
}
